package org.teremail.smtp.commands;

import static org.teremail.message.AddressParser.parseSMTPPostmaster;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.teremail.message.Address;
import org.teremail.message.AddressFormatException;
import org.teremail.smtp.SMTPCommandFactory;
import org.teremail.smtp.SMTPSession;

/**
 * Recipient command.  The TO portion of the command will be captured as
 * a single parameter.
 * 
 * @author Michael Barker
 *
 */
public class RCPTCommand extends SMTPCommand {

    private final static Pattern TO_PATTERN = Pattern.compile("TO:(.*)");
    private final static String MSG_501_INVALID_ADDRESS = "501 Invalid address";
    private static final String MSG_501_MISSING_ADDRESS = "501 No address specified";
    
    public RCPTCommand(List<String> parameters) {
        super("RCPT", parameters);
    }

    @Override
    public void process(SMTPSession session) {
        
        if (getParameters().size() > 0) {
            
            try {
                
                String param = getParameters().get(0);
                Matcher m = TO_PATTERN.matcher(param);
                if (m.matches() && m.groupCount() == 1) {
                    Address address = parseSMTPPostmaster(m.group(1));
                    session.addRecipient(address);
                    session.write(MSG_OK);
                } else {
                    session.write(MSG_501_INVALID_ADDRESS);
                }
                
            } catch (AddressFormatException e) {
                session.write(MSG_501_INVALID_ADDRESS);
            }
        } else {
            session.write(MSG_501_MISSING_ADDRESS);
        }
                
    }

    public static final SMTPCommandFactory FACTORY = new SMTPCommandFactory() {
        public SMTPCommand create(List<String> parameters) {
            return new RCPTCommand(parameters);
        }
    };

}
